//
//  RAFSUTestViewController.m
//  RAFSUManagement
//
//  Created by Piccolo on 27/03/2018.
//  Copyright © 2018 Rayonics. All rights reserved.
//

#import "RAFSUTestViewController.h"
#import "RAFSUSimCardModel.h"
#import "RAFSUHardwareModel.h"
#import "RAFSUDetectInfoView.h"

#import "BMScanStyle1VC.h"
#import "BMScanViewController.h"
#import "BMScanDefaultCotroller.h"
#import "BMZDYVC.h"
#import "BMScanCodeManagerVC.h"

static const NSString *kGJSerial = @"001";
static const NSString *kWellLidSerial = @"002";

typedef NS_ENUM(NSUInteger, NSRATestFSUVerifyStatus){
    
    NSRATestFSUVerifyStatusNotScanned = 0x01,
    NSRATestFSUVerifyStatusVerifying = 0x02,
    NSRATestFSUVerifyStatusQRCodeNotSameAsBarCode = 0x03,
    NSRATestFSUVerifyStatusFSUInfoNotSameAsQRCodeIMEI = 0x04,
    NSRATestFSUVerifyStatusFSUInfoNotSameAsQRCodeIMSI = 0x05,
    NSRATestFSUVerifyStatusFSUInfoNotSameAsQRCodeMacAddress = 0x06,
    NSRATestFSUVerifyStatusNormal = 0x07,
};

typedef NS_ENUM(NSUInteger, NSRATestFSUTestStep){
    
    NSRATestFSUTestStepBasic = 0x01,
    NSRATestFSUTestStepNBIoT = 0x02,
    NSRATestFSUTestStepUpdateHardWare = 0x03,
};

typedef NS_ENUM(NSUInteger, NSRAFSUStatus) {
    
    NSRAFSUStatusNormal = 0x00,//0000
    NSRAFSUStatusCylinderIIUnlock = 0x01,//0001
    NSRAFSUStatusCylinderIUnlock = 0x02,//0010
    NSRAFSUStatusCylinderICylinderIIUnlock = 0x03,//0011
    NSRAFSUStatusContactIIUnlock = 0x04,//0100
    NSRAFSUStatusLockIIUnlock = 0x05,//0101
    NSRAFSUStatusContactIICylinderIUnlock = 0x06,//0110
    NSRAFSUStatusContactIICylinderICylinderIIUnlock = 0x07,//0111
    NSRAFSUStatusContactIUnlock = 0x08,//1000
    NSRAFSUStatusContactICylinderIIUnlock = 0x09,//1001
    NSRAFSUStatusLockIUnlock = 0x0a,//1010
    NSRAFSUStatusContactICylinderICylinderIIUnlock = 0x0b,//1011
    NSRAFSUStatusContactIContactIIUnlock = 0x0c,//1100
    NSRAFSUStatusContactIContactIICylinderIIUnlock = 0x0d,//1101
    NSRAFSUStatusContactIContactIICylinderIUnlock = 0x0e,//1110
    NSRAFSUStatusContactIContactIICylinderICylinderIIUnlock = 0x0f, //1111
    NSRAFSUStatusShake = 0x10,
    NSRAFSUStatusError = 0x11,
    
};

typedef struct {
    
    int firstLockIllegalUnlockEventCount;
    int firstLockBleUnlockEventCount;
    int secondLockIllegalUnlockEventCount;
    int secondLockBleUnlockEventCount;
    int shakeEventCount;
} RAFSUEventCountStruct;


@interface RAFSUTestViewController () <RABleServiceControllerDelegate, BMScanViewControllerDelegate> {
    
    RAFSUSDKPeripheral *_currentBle;
    DGActivityIndicatorView *_indicator;
    RAFSUDetectInfoView *_detectInfoView;
    RAFSUSimCardModel *_simCardModel;
    RAFSUHardwareModel *_hardwareInfo;
    RAFSUCodeModel *_fsuCodeModel;
    NSRATestFSUVerifyStatus _verifyStatus;
    NSRATestFSUTestStep _testStep;
    RAFSUSDKDetectInfo *_fsuDetectInfo;
    RAFSUSDKLockInfo *_lock1;
    RAFSUSDKLockInfo *_lock2;
    NSRAFSUStatus _fsuStatus;
    RAFSUEventCountStruct _eventCountStruct;
    NSInteger _subStep;
    NSString *_fsuDeviceId;
    BOOL _didSetFSUTime;
    BOOL _didSendReadFSUDeviceID;
    BOOL _updateDeviceID;
    BOOL _didReadSimCardInfo;
    BOOL _isReadingFSUEvent;
    NSUInteger _reReadSimCardInfoTimes;
    NSUInteger _reReadMacAndVersionTimes;
    UIButton *_basicTestBtn;
    UIButton *_nbTestBtn;
    UIButton *_updateTestBtn;
    UIButton *_retestBtn;
    UIButton *_registerBtn;
    
    NSString *_peripheralNameBuffer;
    BOOL _basicTestPassed;
    BOOL _nbTestPassed;
    BOOL _updateTestPassed;
    NSString *_nbTestResultString;
    
    __weak IBOutlet UILabel *_verifyStatusLabel;
    __weak IBOutlet UILabel *_bleStatusLabel;
    
}


@end

@implementation RAFSUTestViewController

- (void)viewDidLoad {
    // Do any additional setup after loading the view from its nib.
    [super viewDidLoad];
    [RANetWorkServiceController.sharedManager startNetWorkDetectionService];
    [self setupInitalization];
    [self setupIndicator];
    [self setupNavigationBar];
    [self setupDetectInfoView];
//    [self updateVerifyLabelFromVerifyStatus:NSRATestFSUVerifyStatusNotScanned];
    [self startFSUVerifyStatusDetecting];
    [self setupTestBtns];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setupFSUSDK];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self disconnectBle];
}

#pragma mark - Utils

- (void)startFSUVerifyStatusDetecting {
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        while (self) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self updateBleStatusLabelFromBleConnected:[RABleUtil bluetoothIsConnected]];
                [self updateVerifyLabelFromVerifyStatus:_verifyStatus];
                if (![RABleUtil bluetoothIsConnected]) {
                    if (_verifyStatus != NSRATestFSUVerifyStatusVerifying) {
                        _verifyStatus = NSRATestFSUVerifyStatusNotScanned;
                    }
                    [self updateNavigationTitle:@""];
                    _detectInfoView.hidden = YES;
                } else {
                    [self updateNavigationTitle:_currentBle.peripheralName];
                }
            });
            [NSThread sleepForTimeInterval:.5f];
        }
    });
}

- (void)setupFSUSDK {
    
    [RABleServiceController.sharedManager initBleServiceWithDelegate:self];
}

- (void)setupInitalization {
    
    _verifyStatus = NSRATestFSUVerifyStatusNotScanned;
    self.automaticallyAdjustsScrollViewInsets = NO;
    _basicTestPassed = NO;
    _nbTestPassed = NO;
    _updateTestPassed = YES;
}

- (void)setupIndicator {
    
    _indicator = [RAUtil newIndicatorWithTarget:self centerPoint:CGPointMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 3)];
}

- (void)setupNavigationBar {
    
    self.navigationController.navigationBarHidden = NO;
    [self setupNavigationBarBtn];
}

- (void)setupNavigationBarBtn {
    
    UIButton *scanBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    scanBtn.frame = CGRectMake(0, 0, 40, 20);
    [scanBtn addTarget:self action:@selector(scanBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [scanBtn setTitle:@"扫描" forState:UIControlStateNormal];
    [scanBtn sizeToFit];
    
    UIBarButtonItem *connectBtnItem = [[UIBarButtonItem alloc] initWithCustomView:scanBtn];
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:connectBtnItem, nil];
}

- (void)updateNavigationTitle:(NSString *)title {
    
    if (![title isEqualToString:self.navigationItem.title]) {
        self.navigationItem.title = title;
    }
}

- (void)setupDetectInfoView {
    
    _detectInfoView = [RAFSUDetectInfoView createViewFromNib];
    _detectInfoView.hidden = YES;
    [RAUtil setDownView:_detectInfoView aboveView:_verifyStatusLabel spacing:INNER_BOUNDS_SPACING];
    [self.view addSubview:_detectInfoView];
}

//- (void)startScanQRCode {
//
//
//}

- (void)startScanBarCode {
    
    [self disconnectBle];
    [self pushWithScanLinAnimation:BMScanLinTypeReticular1 scanType:BMScanTypeBarCode];
}

- (void)startScanBle {
    
    if ([RABleUtil bluetoothIsConnected]) {
        [self disconnectBle];
        [NSThread sleepForTimeInterval:.2f];
    }
    [RABleServiceController.sharedManager startScanBle];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kScanDurationTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (![RABleUtil bluetoothIsConnected]) {
            NSString *messageString = [NSString stringWithFormat:@"附近没有名为%@的蓝牙", _fsuCodeModel.peripheralName];
            [RAUtil showAlertWithMessage:messageString alertType:NSRAAlertTypeError];
            [RAUtil setIndicator:_indicator hidden:YES target:self aboveSubView:nil];
        }
    });
}

- (void)stopScan {
    
    [RABleServiceController.sharedManager stopScan];
}

- (void)updateBleStatusLabelFromBleConnected:(BOOL)bleConnected {
    
    NSString *statusString = bleConnected ? @"已连接" : @"未连接";
    UIColor *textColor = bleConnected ? [UIColor greenColor] : [UIColor redColor];
    _bleStatusLabel.text = [NSString stringWithFormat:@"蓝牙状态:%@",statusString];
    _bleStatusLabel.textColor = textColor;
}

- (void)updateVerifyLabelFromVerifyStatus:(NSRATestFSUVerifyStatus)status {
    
    NSString *statusString = @"";
    UIColor *textColor = [UIColor redColor];
    statusString = [self verifyStringFromVerifyStatus:status];
    _verifyStatusLabel.text = [NSString stringWithFormat:@"验证状态:%@",statusString];
    if (status == NSRATestFSUVerifyStatusNormal) {
        textColor = [UIColor greenColor];
    } else if (status == NSRATestFSUVerifyStatusVerifying) {
        textColor = [UIColor orangeColor];
    }
    _verifyStatusLabel.textColor = textColor;
}

- (NSString *)verifyStringFromVerifyStatus:(NSRATestFSUVerifyStatus)verifyStatus {
    
    NSString *statusString = @"";
    switch (verifyStatus) {
        case NSRATestFSUVerifyStatusNotScanned:
            statusString = @"未扫描";
            break;
        case NSRATestFSUVerifyStatusVerifying:
            statusString = @"验证中...";
            break;
        case NSRATestFSUVerifyStatusQRCodeNotSameAsBarCode:
            statusString = @"扫码验证失败";
            break;
        case NSRATestFSUVerifyStatusFSUInfoNotSameAsQRCodeIMEI:
            statusString = @"IMEI验证不符";
            break;
        case NSRATestFSUVerifyStatusFSUInfoNotSameAsQRCodeIMSI:
            statusString = @"IMEI验证不符";
            break;
        case NSRATestFSUVerifyStatusFSUInfoNotSameAsQRCodeMacAddress:
            statusString = @"MacAddress验证不符";
            break;
        case NSRATestFSUVerifyStatusNormal:
            statusString = @"验证成功";
            break;
        default:
            statusString = @"未扫描";
            break;
    }
    return statusString;
}

- (void)delayReadSimpleFSUDeviceIDAfterSecond:(CGFloat)second {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(second * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
        if (!_updateDeviceID && !_didSendReadFSUDeviceID) {
            [RASimpleFSUSDK readFSUDeviceID];
            _didSendReadFSUDeviceID = YES;
        }
    });
}

- (BOOL)verifyFSUInfoAsBarCodeAndQRCode {
    
    BOOL verifyMacAddress = [_hardwareInfo.macAddress isEqualToString:_fsuCodeModel.macAddress];
    BOOL verifyIMEI = [_simCardModel.IMEI isEqualToString:_fsuCodeModel.IMEI];
    BOOL verifyIMSI = [_simCardModel.IMSI isEqualToString:_fsuCodeModel.IMSI];
    [RAUtil setIndicator:_indicator hidden:YES target:self aboveSubView:nil];
    if (verifyMacAddress && verifyIMEI && verifyIMSI) {
        _verifyStatus = NSRATestFSUVerifyStatusNormal;
        //验证通过,开始测试
        _detectInfoView.hidden = NO;
        return YES;
    } else {
        if (!verifyIMEI) {
            _verifyStatus = NSRATestFSUVerifyStatusFSUInfoNotSameAsQRCodeIMEI;
        } else if (!verifyIMSI) {
            _verifyStatus = NSRATestFSUVerifyStatusFSUInfoNotSameAsQRCodeIMSI;
        } else if (!verifyMacAddress) {
            _verifyStatus = NSRATestFSUVerifyStatusFSUInfoNotSameAsQRCodeMacAddress;
        }
        [self disconnectBle];
    }
    return NO;
}

- (void)setupTestBtns {
    
    _basicTestBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_basicTestBtn ra_setWidth:(SCREEN_WIDTH - INNER_BOUNDS_SPACING * 3.f) / 3.f];
    [_basicTestBtn ra_setHeight:30.f];
    [_basicTestBtn ra_setOriginX:INNER_BOUNDS_SPACING];
    [_basicTestBtn addTarget:self action:@selector(basicTestBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_basicTestBtn setTitle:@"基础测试" forState:UIControlStateNormal];
    [RAUtil setDownView:_basicTestBtn aboveView:_detectInfoView spacing:INNER_BOUNDS_SPACING];
    
    _nbTestBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_nbTestBtn addTarget:self action:@selector(nbTestBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_nbTestBtn setTitle:@"NB测试" forState:UIControlStateNormal];
    [RAUtil setRightView:_nbTestBtn nextToView:_basicTestBtn sameFrame:YES spacing:INNER_BOUNDS_SPACING];
    
    _updateTestBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _updateTestBtn.enabled = NO;
    [_updateTestBtn addTarget:self action:@selector(updateTestBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_updateTestBtn setTitle:@"升级测试" forState:UIControlStateNormal];
    [RAUtil setRightView:_updateTestBtn nextToView:_nbTestBtn sameFrame:YES spacing:INNER_BOUNDS_SPACING];
    
    _retestBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_retestBtn ra_setWidth:(SCREEN_WIDTH - INNER_BOUNDS_SPACING * 3.f) / 3.f];
    [_retestBtn ra_setHeight:30.f];
    [_retestBtn ra_setOriginX:INNER_BOUNDS_SPACING];
    [_retestBtn addTarget:self action:@selector(retestBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_retestBtn setTitle:@"重测" forState:UIControlStateNormal];
    [RAUtil setDownView:_retestBtn aboveView:_basicTestBtn spacing:INNER_BOUNDS_SPACING];
    
    _registerBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_registerBtn addTarget:self action:@selector(registerBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    [RAUtil setRightView:_registerBtn nextToView:_retestBtn sameFrame:YES spacing:INNER_BOUNDS_SPACING];
    
    [self.view addSubview:_basicTestBtn];
    [self.view addSubview:_nbTestBtn];
    [self.view addSubview:_updateTestBtn];
    [self.view addSubview:_retestBtn];
    [self.view addSubview:_registerBtn];
}

- (void)disconnectBle {
    
    _didSetFSUTime = NO;
    _didSendReadFSUDeviceID = NO;
    _updateDeviceID = NO;
    _didReadSimCardInfo = NO;
    _isReadingFSUEvent = NO;
    _verifyStatus = NSRATestFSUVerifyStatusNotScanned;
    [RAUtil setIndicator:_indicator hidden:YES target:self aboveSubView:nil];
    [RABleUtil disconnectBle];
}

- (void)setDeviceIDFromResponseObject:(NSDictionary *)responseObject {
    
    NSString *deviceID = responseObject[@"data"][@"number"];
    if ([RAUtil checkStringExist:deviceID]) {
        [RASimpleFSUSDK setFSUDeviceID:deviceID];
    } else {
        [RAUtil showAlertWithMessage:@"注册失败" alertType:NSRAAlertTypeError];
    }
}

#pragma mark - Button Function

- (void)scanBtnOnClick:(UIButton *)button {
    
    [self pushWithScanLinAnimation:BMScanLinTypeReticular1 scanType:BMScanTypeBarCode];
}

#pragma mark - BMScan

- (void)pushWithScanLinAnimation:(BMScanLin)scanLin scanType:(BMScanType)scanType {
    BMScanViewController *scanViewController = [BMScanViewController new];
    scanViewController.scanLinType = scanLin;
    scanViewController.scanType = scanType;
    scanViewController.delegate = self;
    [self.navigationController pushViewController:scanViewController animated:YES];
}

- (void)basicTestBtnOnClick:(UIButton *)button {
    
    if ([RABleUtil bluetoothIsConnected]) {
        [self basicStep];
    } else {
        [self startScanBarCode];
    }
}

- (void)nbTestBtnOnClick:(UIButton *)button {
    
    if ([RABleUtil bluetoothIsConnected]) {
        [self nbStep];
    } else {
        [self startScanBarCode];
    }
}

- (void)updateTestBtnOnClick:(UIButton *)button {
    
    
}

- (void)retestBtnOnClick:(UIButton *)button {
    
    [self resetTestStatus];
    [RAUtil showAlertWithMessage:@"重置成功" alertType:NSRAAlertTypeSuccessful];
}

- (void)registerBtnOnClick:(UIButton *)button {
    
//    [self getDeviceID];
//    return;
    NSString *notTestTypeString = @"";
    if (!_basicTestPassed || !_nbTestPassed || !_updateTestPassed) {
        if (!_basicTestPassed) {
            notTestTypeString = [notTestTypeString stringByAppendingString:@"基本测试"];
            if (!_nbTestPassed || !_updateTestPassed) {
                notTestTypeString = [notTestTypeString stringByAppendingString:@"\n"];
            }
        }
        if (!_nbTestPassed) {
            notTestTypeString = [notTestTypeString stringByAppendingString:@"NB测试"];
            if (!_updateTestPassed) {
                notTestTypeString = [notTestTypeString stringByAppendingString:@"\n"];
            }
        }
        if (!_updateTestPassed) {
            notTestTypeString = [notTestTypeString stringByAppendingString:@"升级测试"];
        }
        [RAUtil showAlertWithMessage:[NSString stringWithFormat:@"以下测试尚未完成:\n%@", notTestTypeString] alertType:NSRAAlertTypeError];
    } else {
        [self getDeviceID];
    }
}


#pragma mark - BMScanViewControllerDelegate

- (void)scannedFSUCodeModel:(RAFSUCodeModel *)fsuCodeModel {
    
    if (!fsuCodeModel) {
        _verifyStatus = NSRATestFSUVerifyStatusQRCodeNotSameAsBarCode;
        [RAUtil showAlertWithMessage:[self verifyStringFromVerifyStatus:NSRATestFSUVerifyStatusQRCodeNotSameAsBarCode] alertType:NSRAAlertTypeError];
    } else {
        _fsuCodeModel = fsuCodeModel;
        [self startScanBle];
        [RAUtil setIndicator:_indicator hidden:NO target:self aboveSubView:self.view];
        _verifyStatus = NSRATestFSUVerifyStatusVerifying;
    }
}

#pragma mark - RABleServiceControllerDelegate

- (void)scanedPeripheral:(CBPeripheral *)peripheral peripheralName:(NSString *)peripheralName RSSI:(NSNumber *)RSSI {

    NSLog(@"@270比对中:%@<-->%@", peripheralName, _fsuCodeModel.peripheralName);
    if ([peripheralName isEqualToString:_fsuCodeModel.peripheralName]) {
        _currentBle = [[RAFSUSDKPeripheral alloc] initWithPeripheral:peripheral peripheralName:peripheralName RSSI:RSSI];
        if ([_peripheralNameBuffer isEqualToString:peripheralName]) {
            _peripheralNameBuffer = peripheralName;
            [self resetTestStatus];
        }
        
        [RABleUtil stopScanAndInitSDKFromPeripheral:_currentBle];
    }
}
- (void)currentFSURssi:(NSNumber *)rssi{
    
}

#pragma mark - Simple FSU

/**
 初始化SDK
 */
- (void)simpleFsuRequestInitSdkResultInfo:(RAFSUSDKResultInfo *)info {
    
    [RASimpleFSUSDK connectBlueTooth:_currentBle.peripheral withSyscode:DEFINE_SYSCODE withRegcode:DEFINE_REGCODE];
}

/**
 连接成功
 */
- (void)simpleFsuRequestConnectResultInfo:(RAFSUSDKResultInfo *)info {
    
    if (info.feedBackState) {
        NSLog(@"@232连接上了");
        [self delayReadSimpleFSUDeviceIDAfterSecond:5.f];
    } else {
        NSLog(@"@526失败");
    }
}

/**
 连接断开
 */
- (void)simpleFsuRequestDisconnectResultInfo:(RAFSUSDKResultInfo *)info {
    
    
    
}

/**
 主动上报
 */
- (void)simpleFsuRequestActiveReport:(RAFSUSDKActiveReportInfo *)fsuActiveReportInfo {
   
    [self delayReadSimpleFSUDeviceIDAfterSecond:.5f];
    BOOL updateDetectInfo = _didSetFSUTime && _didReadSimCardInfo;
    if (updateDetectInfo) {
        _fsuDetectInfo = fsuActiveReportInfo.fsuDetectInfo;
        for (RAFSUSDKLockInfo *fsuLock in _fsuDetectInfo.locksArray) {
            if (fsuLock.serialNumber == 1) {
                _lock1 = fsuLock;
            } else if (fsuLock.serialNumber == 2) {
                _lock2 = fsuLock;
            }
        }
        [_detectInfoView updateViewFromDetectInfo:fsuActiveReportInfo.fsuDetectInfo deviceID:_fsuDeviceId macAddress:_hardwareInfo.macAddress];
    }
}

/**
 读取设备ID
 */
- (void)simpleFsuRequestReadFSUDeviceID:(RAFSUSDKResultInfo *)info {
    
    _didSendReadFSUDeviceID = NO;
    NSString *fsuDeviceID = info.detailDic[@"fsu_device_info"];
    if (![RAUtil checkStringExist:fsuDeviceID]) {
        NSLog(@"@497 读取device id 失败");
        [RASimpleFSUSDK readFSUDeviceID];
        _didSendReadFSUDeviceID = YES;
        return;
    }
    _fsuDeviceId = fsuDeviceID;
    _updateDeviceID = YES;
    [RASimpleFSUSDK setFSUTime];
}

/**
 设置FSU Device ID
 */
- (void)simpleFsuRequestSetFSUDeviceID:(RAFSUSDKResultInfo *)info {
    
    [RAUtil showAlertWithMessage:[NSString stringWithFormat:@"设置注册%@", info.feedBackState ? @"成功" : @"失败"] alertType:info.feedBackState ? NSRAAlertTypeSuccessful : NSRAAlertTypeError];
    if (info.feedBackState) {
        NSString *deviceID = info.detailDic[@"device_id"];
        [self postRegisterDeviceID:deviceID];
    }
}

/**
 设置时间
 */
- (void)simpleFsuRequestSetFsuTimeResultInfo:(RAFSUSDKResultInfo *)info {
    
    _didSetFSUTime = YES;
    [RASimpleFSUSDK readFSUSimCardInfo];
}

/**
 读SIM卡信息
 */
- (void)simpleFsuRequestReadSimCardInfo:(RAFSUSDKResultInfo *)info {
    
    NSLog(@"@670 - %d", info.feedBackState);
    _reReadSimCardInfoTimes ++;
    if (_reReadSimCardInfoTimes == 3) {
        //        [RAUtil showErrorAlertWithTitle:[RAUtil getSingleKeyStr:@"TEXT_ERROR"] message:[RAUtil getSingleKeyStr:@"TEXT_FSU_READ_SIM_CARD_INFO_FAILED"] target:self];
        _reReadSimCardInfoTimes = 0;
        _didReadSimCardInfo = YES;
        [RASimpleFSUSDK readFSUMacAndVersionInfo];
        return;
    }
    if (info.feedBackState) {
        NSDictionary *fsuSimCardInfoDic = info.detailDic;
        _simCardModel = [[RAFSUSimCardModel alloc] initWithFsuSdkSimCardInfoDic:fsuSimCardInfoDic];
        BOOL isNullInfo = ![RAUtil checkStringExist:_simCardModel.IMEI] &&
        ![RAUtil checkStringExist:_simCardModel.IMSI] &&
        ![RAUtil checkStringExist:_simCardModel.SINR] &&
        ![RAUtil checkStringExist:_simCardModel.signalPower] &&
        ![RAUtil checkStringExist:_simCardModel.RSRQ];
        if (!isNullInfo) {
            _didReadSimCardInfo = YES;
            _reReadSimCardInfoTimes = 0;
            [RASimpleFSUSDK readFSUMacAndVersionInfo];
        } else {
            NSLog(@"@254 info 为空,重读中");
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5f * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
                [RASimpleFSUSDK readFSUSimCardInfo];
            });
        }
        
    } else {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5f * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
            [RASimpleFSUSDK readFSUSimCardInfo];
        });
    }
}

/**
 读Mac地址和硬件信息
 */
- (void)simpleFsuRequestReadFSUMacAndVerson:(RAFSUSDKResultInfo *)info {
    
    NSLog(@"@720 - %d - rereadtimes: %ld", info.feedBackState, _reReadMacAndVersionTimes);
    _reReadMacAndVersionTimes ++;
    
    if (_reReadMacAndVersionTimes == 3) {
        _reReadMacAndVersionTimes = 0;
        [RAUtil showAlertWithMessage:[RAUtil getSingleKeyStr:@"TEXT_GET_MAC_ADDRESS_FAILED"] alertType:NSRAAlertTypeError];
        [RAUtil setIndicator:_indicator hidden:YES target:self aboveSubView:nil];
        return;
    }
    
    if (info.feedBackState) {
        NSDictionary *macAndVersionDic = info.detailDic;
        _hardwareInfo = [[RAFSUHardwareModel alloc] initWithMacAddress:macAndVersionDic[@"fsu_mac_address"] softVersion:macAndVersionDic[@"fsu_version"]];
        BOOL isNullInfo = ![RAUtil checkStringExist:_hardwareInfo.macAddress] && ![RAUtil checkStringExist:_hardwareInfo.softVersion];
        if (!isNullInfo) {
            _reReadMacAndVersionTimes = 0;
            [self verifyFSUInfoAsBarCodeAndQRCode];
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5f * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
                [RASimpleFSUSDK readFSUMacAndVersionInfo];
            });
        }
    } else {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5f * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
            [RASimpleFSUSDK readFSUMacAndVersionInfo];
        });
    }
}

/**
 读事件
 */
- (void)simpleFsuRequestReadFSUEvent:(RAFSUSDKResultInfo *)info {
    
    if (info.feedBackState) {
        NSArray *eventArray = info.detailDic[@"fsu_event"];
        for (NSDictionary *eventDic in eventArray) {
            NSRAFsuEventType fsuEventType = (NSRAFsuEventType)[eventDic[@"fsu_event_type"] integerValue];
            switch (fsuEventType) {
                case NSRAFsuEventTypeBluetoothUnlock: {
                    NSString *lockSerial = eventDic[@"fsu_event_lock_id"];
                    if (lockSerial.integerValue == 1) {
                        _eventCountStruct.firstLockBleUnlockEventCount ++;
                    } else if (lockSerial.integerValue == 2) {
                        _eventCountStruct.secondLockBleUnlockEventCount ++;
                    }
                    break;
                }
                case NSRAFsuEventTypeIllegaUnlock: {
                    NSString *lockSerial = eventDic[@"fsu_event_lock_id"];
                    if (lockSerial.integerValue == 1) {
                        _eventCountStruct.firstLockIllegalUnlockEventCount ++;
                    } else if (lockSerial.integerValue == 2) {
                        _eventCountStruct.secondLockIllegalUnlockEventCount ++;
                    }
                    break;
                }
                case NSRAFsuEventTypeShakeWarning: {
                    _eventCountStruct.shakeEventCount ++;
                    break;
                }
                    
                default:
                    break;
            }
        }
        NSString *fsuEventCheckString = @"";
        if (!_eventCountStruct.firstLockBleUnlockEventCount) {
            fsuEventCheckString = [fsuEventCheckString stringByAppendingString:@"锁1蓝牙开门事件缺失\n"];
        }
        if (!_eventCountStruct.secondLockBleUnlockEventCount) {
            fsuEventCheckString = [fsuEventCheckString stringByAppendingString:@"锁2蓝牙开门事件缺失\n"];
        }
        if (!_eventCountStruct.firstLockIllegalUnlockEventCount) {
            fsuEventCheckString = [fsuEventCheckString stringByAppendingString:@"锁1非法事件缺失\n"];
        }
        if (!_eventCountStruct.secondLockIllegalUnlockEventCount) {
            fsuEventCheckString = [fsuEventCheckString stringByAppendingString:@"锁2非法事件缺失\n"];
        }
        if (!_eventCountStruct.shakeEventCount) {
            fsuEventCheckString = [fsuEventCheckString stringByAppendingString:@"震动告警事件缺失\n"];
        }
        if (!fsuEventCheckString.length) {
            _basicTestPassed = YES;
            [RAUtil showAlertWithMessage:@"基础测试完成" alertType:NSRAAlertTypeSuccessful];
        } else {
            [RAUtil showAlertWithMessage:fsuEventCheckString alertType:NSRAAlertTypeError];
        }
        _subStep = 0;
        [self initEventCountStruct];
        
    } else {
        [RAUtil showAlertWithMessage:@"事件读取失败,测试结束" alertType:NSRAAlertTypeError];
        _subStep = 0;
    }
}


/**
 开锁成功
 */
- (void)simpleFsuRequestSetOnlineOpenResultInfo:(RAFSUSDKResultInfo *)info {
    
    if (info.feedBackState) {
        NSLog(@"453开锁成功");
        if (_subStep == 6) {
            [self basicStepSeventh];
        } else if (_subStep == 9) {
            [self basicStepTenth];
        }
        
    } else {
        NSLog(@"456开锁失败");
    }
}

- (void)simpleFsuRequestReadFSUUnvarnishedTransmissionInfo:(RAFSUSDKResultInfo *)info {
    
    if (info.feedBackState) {
        NSString *requestString = @"";
        if ([RAUtil isExistDic:info.detailDic key:@"fsu_unvarnished_transmission_string"]) {
            requestString = info.detailDic[@"fsu_unvarnished_transmission_string"];
            if ([self isNotErrorString:requestString]) {
                switch (_subStep) {
                    case 1: {
                        NSString *IMEI = [requestString substringWithRange:NSMakeRange(6, 15)];
                        _nbTestResultString = [_nbTestResultString stringByAppendingString:[NSString stringWithFormat:@"IMEI:%@\n", IMEI]];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5f * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
                            [self nbStepSecond];
                        });
                        break;
                    }
                    case 2: {
                        NSString *IMSI = [requestString substringWithRange:NSMakeRange(0, 15)];
                        _nbTestResultString = [_nbTestResultString stringByAppendingString:[NSString stringWithFormat:@"IMSI:%@\n", IMSI]];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5f * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
                            [self nbStepThird];
                        });
                        break;
                    }
                    case 3: {
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5f * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
                            [self nbStepFourth];
                        });
                        break;
                    }
                    case 4: {
                        NSString *signPower = [requestString substringWithRange:NSMakeRange(5, 2)];
                        if (signPower.integerValue == 99) {
                            [self showNBTestFailed];
                        } else {
                            _nbTestResultString = [_nbTestResultString stringByAppendingString:[NSString stringWithFormat:@"网络信号强度:%@\n", signPower]];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5f * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
                                [self nbStepFifth];
                            });
                        }
                        break;
                    }
                    case 5: {
                        NSString *netStatusString = [requestString substringWithRange:NSMakeRange(9, 1)];
                        if (netStatusString.integerValue != 1) {
                            [self showNBTestFailed];
                        } else {
                            _nbTestResultString = [_nbTestResultString stringByAppendingString:@"网络连接成功\n"];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5f * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
                                [self nbStepSixth];
                            });
                        }
                        break;
                    }
                    case 6: {
                        NSRange snrRange = [requestString rangeOfString:@"SNR:"];
                        NSRange earfcn = [requestString rangeOfString:@"EARFCN:"];
                        NSString *snrString = [requestString substringWithRange:NSMakeRange(snrRange.location + snrRange.length, earfcn.location - 1 - (snrRange.location + snrRange.length))];
                        CGFloat scr = snrString.integerValue / 10.f;
                        _nbTestResultString = [_nbTestResultString stringByAppendingString:[NSString stringWithFormat:@"信噪比:%.1f\n", scr]];
                        [RAUtil showAlertWithMessage:_nbTestResultString alertType:NSRAAlertTypeSuccessful];
                        _nbTestPassed = YES;
                        _subStep = 0;
                        NSLog(@"OK");
                        break;
                    }
                        
                    default:
                        break;
                }
                if (_subStep < 6) {
                    [SVProgressHUD showProgress:_subStep / 6.f status:_nbTestResultString];
                }
            }
            
        } else {
            [self showNBTestFailed];
        }
    } else {
        [self showNBTestFailed];
    }
}

- (void)simpleFsuRequestCleanFSUEvent:(RAFSUSDKResultInfo *)info {
    
    if (info.feedBackState) {
        [RAUtil showAlertWithMessage:@"清除FSU事件成功" alertType:NSRAAlertTypeSuccessful];
        [self basicStepFirst];
    } else {
        [RAUtil showAlertWithMessage:@"清除FSU事件失败" alertType:NSRAAlertTypeError];
    }
}

#pragma mark - Test Utils

- (void)startActiveReportDetecting {
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        while ([RABleUtil bluetoothIsConnected] && _testStep == NSRATestFSUTestStepBasic && _subStep > 0) {
            
            if (_fsuDetectInfo.fsuShaking) {
                _fsuStatus = NSRAFSUStatusShake;
            } else {
                NSInteger c1 = (_lock1.contactStatus == NSRAFSUSDKLockStatusTypeUnlocked ? 1 : 0) << 3;
                NSInteger c2 = (_lock2.contactStatus == NSRAFSUSDKLockStatusTypeUnlocked ? 1 : 0) << 2;
                NSInteger l1 = (_lock1.cylinderStatus == NSRAFSUSDKLockStatusTypeUnlocked ? 1 : 0) << 1;
                NSInteger l2 = (_lock2.cylinderStatus == NSRAFSUSDKLockStatusTypeUnlocked ? 1 : 0);
                _fsuStatus = (NSRAFSUStatus)(l1 + l2 + c1 + c2);
            }
            [NSThread sleepForTimeInterval:.1f];
        }
    });
}

- (NSString *)fsuStatusStringFromStatus:(NSRAFSUStatus)status {
    
    NSString *statusString = @"";
    switch (status) {
        case NSRAFSUStatusNormal:
            statusString = @"正常";
            break;
        case NSRAFSUStatusCylinderIIUnlock:
            statusString = @"锁芯2打开";
            break;
        case NSRAFSUStatusCylinderIUnlock:
            statusString = @"锁芯1打开";
            break;
        case NSRAFSUStatusCylinderICylinderIIUnlock:
            statusString = @"锁芯1,2打开";
            break;
        case NSRAFSUStatusContactIIUnlock:
            statusString = @"门磁2打开";
            break;
        case NSRAFSUStatusLockIIUnlock:
            statusString = @"锁2全开";
            break;
        case NSRAFSUStatusContactIICylinderIUnlock:
            statusString = @"门磁2,锁芯1打开";
            break;
        case NSRAFSUStatusContactIICylinderICylinderIIUnlock:
            statusString = @"门磁2,锁芯1,2打开";
            break;
        case NSRAFSUStatusContactIUnlock:
            statusString = @"门磁1打开";
            break;
        case NSRAFSUStatusContactICylinderIIUnlock:
            statusString = @"门磁1,锁芯2打开";
            break;
        case NSRAFSUStatusLockIUnlock:
            statusString = @"锁1全开";
            break;
        case NSRAFSUStatusContactICylinderICylinderIIUnlock:
            statusString = @"门磁1,锁芯1,2打开";
            break;
        case NSRAFSUStatusContactIContactIIUnlock:
            statusString = @"门磁1,2打开";
            break;
        case NSRAFSUStatusContactIContactIICylinderIIUnlock:
            statusString = @"门磁1,2,锁芯2打开";
            break;
        case NSRAFSUStatusContactIContactIICylinderIUnlock:
            statusString = @"门磁1,2,锁芯1打开";
            break;
        case NSRAFSUStatusContactIContactIICylinderICylinderIIUnlock:
            statusString = @"锁1,2全开";
            break;
        case NSRAFSUStatusShake:
            statusString = @"震动异常";
            break;
        case NSRAFSUStatusError:
            statusString = @"非法";
            break;
            
        default:
            break;
    }
    return statusString;
}

- (NSString *)nbTestTypeString {
    
    NSString *typeString = @"";
    switch (_subStep) {
        case 1:
            typeString = kSimpleFSUUnvarnishedTransmissionInfoATCGSN;
            break;
        case 2:
            typeString = kSimpleFSUUnvarnishedTransmissionInfoATCIMI;
            break;
        case 3:
            typeString = kSimpleFSUUnvarnishedTransmissionInfoATCGATTI;
            break;
        case 4:
            typeString = kSimpleFSUUnvarnishedTransmissionInfoATCSQ;
            break;
        case 5:
            typeString = kSimpleFSUUnvarnishedTransmissionInfoATCEREG;
            break;
        case 6:
            typeString = kSimpleFSUUnvarnishedTransmissionInfoATNUESTATS;
            break;
            
        default:
            break;
    }
    return typeString;
}

- (void)showErrorAlertFromCurrentStep:(NSRATestFSUTestStep)testStep errorString:(NSString *)errorString {
    
    NSString *errorStepString = @"";
    switch (testStep) {
        case NSRATestFSUTestStepBasic:
            errorStepString = @"基本测试";
            break;
        case NSRATestFSUTestStepNBIoT:
            errorStepString = @"NB测试";
            break;
        case NSRATestFSUTestStepUpdateHardWare:
            errorStepString = @"升级测试";
            break;
            
            
        default:
            break;
    }
    NSString *errorStringTitle = [errorStepString stringByAppendingString:[NSString stringWithFormat:@"(%ld)失败", _subStep]];
    _subStep = 0;
    [RAUtil showAlertWithMessage:[NSString stringWithFormat:@"%@\n%@", errorStringTitle, errorString] alertType:NSRAAlertTypeError];
}

- (void)showNBTestFailed {
    
    [self showErrorAlertFromCurrentStep:NSRATestFSUTestStepNBIoT errorString:[NSString stringWithFormat:@"(%@)测试失败", [self nbTestTypeString]]];
    _subStep = 0;
}

- (BOOL)isNotErrorString:(NSString *)valueString {
    
    if ([RAUtil checkString:valueString containSubString:@"ERROR"]) {
        [self showNBTestFailed];
        return NO;
    } else {
        return YES;
    }
}

- (void)initEventCountStruct {
    
    _eventCountStruct.firstLockIllegalUnlockEventCount = 0;
    _eventCountStruct.firstLockBleUnlockEventCount = 0;
    _eventCountStruct.secondLockIllegalUnlockEventCount = 0;
    _eventCountStruct.secondLockBleUnlockEventCount = 0;
    _eventCountStruct.shakeEventCount = 0;
}

- (void)resetTestStatus {
    
    _basicTestPassed = NO;
    _nbTestPassed = NO;
    _updateTestPassed = YES;
}

#pragma mark - Basic Test

- (void)basicStep {
    
    if (_basicTestPassed) {
        [RAUtil showAlertWithMessage:@"基本测试已通过\n如需重测,请点击重测按钮" alertType:NSRAAlertTypeInfo];
    } else {
        _testStep = NSRATestFSUTestStepBasic;
        _subStep = 0;
        [self initEventCountStruct];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.2f * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
            [RASimpleFSUSDK cleanFSUEvent];
        });
    }
}

//验证是否正常状态
- (void)basicStepFirst {
    
    _subStep = 1;
    [self startActiveReportDetecting];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.2f * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
        if (_fsuStatus != NSRAFSUStatusNormal) {
            [self showErrorAlertFromCurrentStep:NSRATestFSUTestStepBasic errorString:[self fsuStatusStringFromStatus:_fsuStatus]];
        } else {
            [self basicStepSecond];
        }
    });
}

//开门磁1
- (void)basicStepSecond {
    
    _subStep = 2;
    [RAUtil showAlertWithMessage:@"请打开门磁1" alertType:NSRAAlertTypeLoading];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        while (_subStep > 0) {
            if (_fsuStatus == NSRAFSUStatusContactIUnlock) {
                [self basicStepThird];
                break;
            } else if (_fsuStatus != NSRAFSUStatusContactIUnlock && _fsuStatus != NSRAFSUStatusNormal) {
                [self showErrorAlertFromCurrentStep:NSRATestFSUTestStepBasic errorString:[self fsuStatusStringFromStatus:_fsuStatus]];
                break;
            }
            [NSThread sleepForTimeInterval:.1f];
        }
    });
    
}

//关门磁1
- (void)basicStepThird {
    
    _subStep = 3;
    [RAUtil showAlertWithMessage:@"请关闭门磁1" alertType:NSRAAlertTypeLoading];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        while (_subStep > 0) {
            if (_fsuStatus == NSRAFSUStatusNormal) {
                [self basicStepFourth];
                break;
            } else if (_fsuStatus != NSRAFSUStatusContactIUnlock) {
                [self showErrorAlertFromCurrentStep:NSRATestFSUTestStepBasic errorString:[self fsuStatusStringFromStatus:_fsuStatus]];
                break;
            }
            [NSThread sleepForTimeInterval:.1f];
        }
    });
}

//打开门磁2
- (void)basicStepFourth {
    
    _subStep = 4;
    [RAUtil showAlertWithMessage:@"请打开门磁2" alertType:NSRAAlertTypeLoading];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        while (_subStep > 0) {
            if (_fsuStatus == NSRAFSUStatusContactIIUnlock) {
                [self basicStepFifth];
                break;
            } else if (_fsuStatus != NSRAFSUStatusContactIIUnlock && _fsuStatus != NSRAFSUStatusNormal) {
                [self showErrorAlertFromCurrentStep:NSRATestFSUTestStepBasic errorString:[self fsuStatusStringFromStatus:_fsuStatus]];
                break;
            }
            [NSThread sleepForTimeInterval:.1f];
        }
    });
}

- (void)basicStepFifth {
    
    _subStep = 5;
    [RAUtil showAlertWithMessage:@"请关闭门磁2" alertType:NSRAAlertTypeLoading];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        while (_subStep > 0) {
            if (_fsuStatus == NSRAFSUStatusNormal) {
                [self basicStepSixth];
                break;
            } else if (_fsuStatus != NSRAFSUStatusContactIIUnlock) {
                [self showErrorAlertFromCurrentStep:NSRATestFSUTestStepBasic errorString:[self fsuStatusStringFromStatus:_fsuStatus]];
                break;
            }
            [NSThread sleepForTimeInterval:.1f];
        }
    });
}

- (void)basicStepSixth {
    
    _subStep = 6;
    RAFSUSDKOnlineOpenInfo *onlineOpenInfo = [[RAFSUSDKOnlineOpenInfo alloc] initWithUserID:1 lockID:1 beginTime:[NSDate date] endTime:[RAUtil getDateAfterDay:0 hour:1 minute:0 second:0]];
    [RASimpleFSUSDK setOnlineOpen:onlineOpenInfo];
}

- (void)basicStepSeventh {
    
    _subStep = 7;
    [RAUtil showAlertWithMessage:@"开锁命令已下发,请打开锁1\n(请先开锁)" alertType:NSRAAlertTypeLoading];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        while (_subStep > 0) {
            if (_fsuStatus == NSRAFSUStatusLockIUnlock) {
                [self basicStepEighth];
                break;
            } else if (_fsuStatus != NSRAFSUStatusNormal && _fsuStatus != NSRAFSUStatusCylinderIUnlock) {
                [self showErrorAlertFromCurrentStep:NSRATestFSUTestStepBasic errorString:[self fsuStatusStringFromStatus:_fsuStatus]];
                break;
            }
            [NSThread sleepForTimeInterval:.1f];
        }
    });
}

- (void)basicStepEighth {
    
    _subStep = 8;
    [RAUtil showAlertWithMessage:@"请关闭锁1和门磁1(请先关门磁)" alertType:NSRAAlertTypeLoading];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        while (_subStep > 0) {
            if (_fsuStatus == NSRAFSUStatusNormal) {
                [self basicStepNineth];
                break;
            } else if (_fsuStatus != NSRAFSUStatusCylinderIUnlock && _fsuStatus != NSRAFSUStatusLockIUnlock) {
                [self showErrorAlertFromCurrentStep:NSRATestFSUTestStepBasic errorString:[self fsuStatusStringFromStatus:_fsuStatus]];
                break;
            }
            [NSThread sleepForTimeInterval:.1f];
        }
    });
}

- (void)basicStepNineth {
    
    _subStep = 9;
    RAFSUSDKOnlineOpenInfo *onlineOpenInfo = [[RAFSUSDKOnlineOpenInfo alloc] initWithUserID:1 lockID:2 beginTime:[NSDate date] endTime:[RAUtil getDateAfterDay:0 hour:1 minute:0 second:0]];
    [RASimpleFSUSDK setOnlineOpen:onlineOpenInfo];
}

- (void)basicStepTenth {
    
    _subStep = 10;
    [RAUtil showAlertWithMessage:@"开锁命令已下发,请打开锁2\n(请先开锁)" alertType:NSRAAlertTypeLoading];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        while (_subStep > 0) {
            if (_fsuStatus == NSRAFSUStatusLockIIUnlock) {
                [self basicStepEleventh];
                break;
            } else if (_fsuStatus != NSRAFSUStatusNormal && _fsuStatus != NSRAFSUStatusCylinderIIUnlock) {
                [self showErrorAlertFromCurrentStep:NSRATestFSUTestStepBasic errorString:[self fsuStatusStringFromStatus:_fsuStatus]];
                break;
            }
            [NSThread sleepForTimeInterval:.1f];
        }
    });
}

- (void)basicStepEleventh {
    
    _subStep = 11;
    [RAUtil showAlertWithMessage:@"请关闭锁2和门磁2(请先关闭门磁)" alertType:NSRAAlertTypeLoading];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        while (_subStep > 0) {
            if (_fsuStatus == NSRAFSUStatusNormal) {
                [self basicStepTwelfth];
                break;
            } else if (_fsuStatus != NSRAFSUStatusCylinderIIUnlock && _fsuStatus != NSRAFSUStatusLockIIUnlock) {
                [self showErrorAlertFromCurrentStep:NSRATestFSUTestStepBasic errorString:[self fsuStatusStringFromStatus:_fsuStatus]];
                break;
            }
            [NSThread sleepForTimeInterval:.1f];
        }
    });
}

- (void)basicStepTwelfth {
    
    _subStep = 12;
    [RAUtil showAlertWithMessage:@"请摇晃FSU" alertType:NSRAAlertTypeLoading];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        while (_subStep > 0) {
            if (_fsuStatus == NSRAFSUStatusShake) {
                [self basicStepThirteenth];
                break;
            } else if (_fsuStatus != NSRAFSUStatusNormal) {
                [self showErrorAlertFromCurrentStep:NSRATestFSUTestStepBasic errorString:[self fsuStatusStringFromStatus:_fsuStatus]];
                break;
            }
            [NSThread sleepForTimeInterval:.1f];
        }
    });
}

- (void)basicStepThirteenth {
    
    _subStep = 13;
    [RAUtil showAlertWithMessage:@"请静止FSU" alertType:NSRAAlertTypeLoading];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        while (_subStep > 0) {
            if (_fsuStatus == NSRAFSUStatusNormal) {
                [self basicStepFourteenth];
                break;
            } else if (_fsuStatus != NSRAFSUStatusShake) {
                [self showErrorAlertFromCurrentStep:NSRATestFSUTestStepBasic errorString:[self fsuStatusStringFromStatus:_fsuStatus]];
                break;
            }
            [NSThread sleepForTimeInterval:.1f];
        }
    });
}

- (void)basicStepFourteenth {
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        while (_subStep > 0) {
            if (_fsuStatus != NSRAFSUStatusNormal) {
                [self showErrorAlertFromCurrentStep:NSRATestFSUTestStepBasic errorString:[self fsuStatusStringFromStatus:_fsuStatus]];
                break;
            }
            [NSThread sleepForTimeInterval:.1f];
        }
    });
    [RASimpleFSUSDK readFSUEvent];
    [RAUtil showAlertWithMessage:@"事件核对中,请勿操作FSU" alertType:NSRAAlertTypeLoading];
//    _basicTestPassed = YES;
//    [RAUtil showAlertWithMessage:@"测试完成" alertType:NSRAAlertTypeSuccessful];
}

- (void)basicStepFifteenth {
    
    
}

- (void)basicStepSixteenth {
    
    
}

- (void)basicStepSevenTeenth {
    
    
}

#pragma mark - NBTest

- (void)nbStep {
    
    if (_nbTestPassed) {
        [RAUtil showAlertWithMessage:@"NB测试已通过\n如需重测,请点击重测按钮" alertType:NSRAAlertTypeInfo];
    } else {
        _nbTestResultString = @"";
        _testStep = NSRATestFSUTestStepNBIoT;
        [self nbStepFirst];
    }
}

- (void)nbStepFirst {
    
    _subStep = 1;
    [RASimpleFSUSDK sendFSUUnvarnishedTransmissionInfo:[self nbTestTypeString]];
}

- (void)nbStepSecond {
    
    _subStep = 2;
    [RASimpleFSUSDK sendFSUUnvarnishedTransmissionInfo:[self nbTestTypeString]];

}

- (void)nbStepThird {
    
    _subStep = 3;
    [RASimpleFSUSDK sendFSUUnvarnishedTransmissionInfo:[self nbTestTypeString]];

}

- (void)nbStepFourth {
    
    _subStep = 4;
    [RASimpleFSUSDK sendFSUUnvarnishedTransmissionInfo:[self nbTestTypeString]];
}

- (void)nbStepFifth {
    
    _subStep = 5;
    [RASimpleFSUSDK sendFSUUnvarnishedTransmissionInfo:[self nbTestTypeString]];
}

- (void)nbStepSixth {
    
    _subStep = 6;
    [RASimpleFSUSDK sendFSUUnvarnishedTransmissionInfo:[self nbTestTypeString]];
}

#pragma mark - Net Work

- (void)getDeviceID {
    
    NSString *macAddress = _hardwareInfo.macAddress;
    NSString *bleName = _currentBle.peripheralName;
    NSString *IMEI = _simCardModel.IMEI;
    NSString *IMSI = _simCardModel.IMSI;
    NSString *version = _hardwareInfo.softVersion;
    NSString *subSerialBleName = [bleName substringWithRange:NSMakeRange(4, 3)];
    NSRAFSUControlType fsuControlType = (NSRAFSUControlType)subSerialBleName.integerValue;
    NSString  *type = [RAUtil stringFromFSUControlType:fsuControlType];
    NSString *factory = @"湖南康普";
    NSString *model = [bleName substringWithRange:NSMakeRange(0, 7)];
    NSString *serialNumber = IMEI;
    NSString *city = [_fsuCodeModel.city substringWithRange:NSMakeRange(0, _fsuCodeModel.city.length - 1)];
    NSDictionary *bodyDic = [NSDictionary dictionaryWithObjectsAndKeys:macAddress, @"mac", bleName, @"blename", IMEI, @"imei", IMSI, @"imsi", version, @"version", type, @"type", factory, @"factory", model, @"model", serialNumber, @"serialNumber", city, @"city", nil];
    NSString *URLString = URL_POST_APPLY_DEVICE_ID;
    [RANetWorkUtil POST:URLString parameters:bodyDic progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        if ([RAUtil requestIsSuccessful:responseObject] || [RAUtil checkString:responseObject[@"msg"] containSubString:@"The device has been register before"]) {
            [self setDeviceIDFromResponseObject:responseObject];
        } else {
            [RAUtil showAlertWithMessage:responseObject[@"msg"] alertType:NSRAAlertTypeError];
        }
    } failure:^(NSURLSessionTask *task, NSError *error) {
        [RAUtil showAlertWithMessage:@"注册失败" alertType:NSRAAlertTypeError];
        NSLog(@"@261 Error: %@", [error localizedDescription]);
    }];
    
    
}

- (void)postRegisterDeviceID:(NSString *)deviceID {
    
    NSString *macAddress = _hardwareInfo.macAddress;
    NSDictionary *bodyDic = [NSDictionary dictionaryWithObjectsAndKeys:macAddress, @"mac", deviceID, @"number", nil];
    NSString *URLString = URL_POST_CONFIRM_DEVICE_ID;
    [RANetWorkUtil POST:URLString parameters:bodyDic progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        if ([RAUtil requestIsSuccessful:responseObject] || [RAUtil checkString:responseObject[@"msg"] containSubString:@"The device has been register before"]) {
            _fsuDeviceId = deviceID;
            [RAUtil showAlertWithMessage:@"注册成功" alertType:NSRAAlertTypeSuccessful];
        } else {
            [RAUtil showAlertWithMessage:responseObject[@"msg"] alertType:NSRAAlertTypeError];
        }
    } failure:^(NSURLSessionTask *task, NSError *error) {
        [RAUtil showAlertWithMessage:@"注册失败" alertType:NSRAAlertTypeError];
        NSLog(@"@261 Error: %@", [error localizedDescription]);
    }];
}
@end
